/*
 * Author: yezi
 * E-mail: okye328@gmail.com
 * Create time: Jan 1, 2013 10:29:35 AM
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package com.kanbox.linux.operation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetworkMeter implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(NetworkMeter.class);

	private long beginTime;
	private long lastTime;
	private int totalDataCount;
	private int lastDataCount;
	private String message;

	private boolean toStop = false;

	public NetworkMeter(String message) {
		this.message = message;
		beginTime = lastTime = System.currentTimeMillis();
		totalDataCount = lastDataCount = 0;
	}

	public void setToStop(boolean toStop) {
		this.toStop = toStop;
	}

	public void addDataCount(int dataCount) {
		lastDataCount += dataCount;
	}

	@Override
	public void run() {
		while (!toStop) {
			print();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void print() {
		long timeDelta = System.currentTimeMillis() - lastTime;
		if (timeDelta == 0)
			return;
		double rate = (double) lastDataCount / (double) timeDelta;// B/ms means
																	// KB/s
		rate = Math.round(rate * 100.0) / 100.0;
		String outMess = message + " at " + rate + " KB/s";
		logger.info(outMess);
		reset();
	}

	private void reset() {
		lastTime = System.currentTimeMillis();
		totalDataCount += lastDataCount;
		lastDataCount = 0;
	}
}
